package cn.itcast.itcaststore.web.servlet;

import cn.itcast.itcaststore.domain.Orderitem;
import cn.itcast.itcaststore.domain.Orders;
import cn.itcast.itcaststore.service.Impl.IOrderService;
import cn.itcast.itcaststore.service.Impl.IOrderitemService;
import cn.itcast.itcaststore.service.OrderService;
import cn.itcast.itcaststore.service.OrderitemService;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.Map;

@WebServlet("/CreateOrderServlet")
public class CreateOrderServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Map<String, String[]> parameterMap = request.getParameterMap();
        Orders orders = new Orders();

        try {
            BeanUtils.populate(orders, parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        Date date = new Date();
        orders.setOrdertime(date);
        orders.setId(date.getTime());
        OrderService orderService = new IOrderService();
        orderService.createOrders(orders);

        String[] product_names = parameterMap.get("product_id");
        Orderitem orderitem = new Orderitem();
        OrderitemService iOrderitemService = new IOrderitemService();

        int i=-1;

        for (String product_name : product_names) {
            i++;
            orderitem.setOrder_id(orders.getId());
            orderitem.setBuynum(Integer.parseInt(parameterMap.get("buynum")[i]));
            orderitem.setProduct_id(product_name);
            iOrderitemService.createOrderitem(orderitem);
        }

        request.setAttribute("order_id",orders.getId());
        request.setAttribute("type","id" );
        request.getSession().removeAttribute("card");
        request.getRequestDispatcher("/ShowOrdersServlet").forward(request,response);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
